package com.chen.common.satoken.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.stp.StpUtil;
import com.chen.base.utils.DutyLinkUtil;
import com.chen.common.satoken.provider.AuthAbsProvider;
import com.chen.common.satoken.params.LoginParam;
import com.chen.root.base.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.v3.oas.annotations.Operation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 登录认证
 * @author: Long
 * @date: 2023/7/5 20:53
 **/
@Slf4j
@RestController
@RequestMapping("/auth")
@Api(value = "auth",tags = "SaToken授权API")
public class AuthController {

    @SaIgnore
    @PostMapping("/login")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "authType",value = "授权类型",dataType = "String",required = true),
            @ApiImplicitParam(name = "authParamMap",value = "需要认证的参数",dataType = "Map",required = true)
    })
    @Operation(summary = "登录",description = "登录")
    public R<Object> login(@RequestBody LoginParam param) throws Exception {
        Object userId = DutyLinkUtil.run(AuthAbsProvider.class, param);
        // 会话登录：参数填写要登录的账号id，建议的数据类型：long | int | String， 不可以传入复杂类型，如：User、Admin 等等
        if (userId != null){
            StpUtil.login(userId);
            return R.ok(StpUtil.getTokenValue(),"登录成功");
        }

        return R.failed(null, "登录失败！参数不合法...");
    }

    @PostMapping("/logout")
    @Operation(summary = "登出",description = "登出")
    public R<Object> logout(){
        // StpUtil.checkLogin(); 检验当前会话是否已经登录, 如果未登录，则抛出异常：`NotLoginException`
        // 获取当前会话是否已经登录，返回true=已登录，false=未登录
        if (StpUtil.isLogin()){
            // 当前会话注销登录
            StpUtil.logout();
        }

        return R.ok(null, "登出成功！");
    }
}
